"""
汽车信息卡片组件
用于展示单个汽车的详细信息
"""

from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QLabel,
                             QPushButton, QFrame, QSizePolicy, QMessageBox)
from PyQt5.QtCore import Qt, pyqtSignal, QUrl
from PyQt5.QtGui import QPixmap, QFont, QPalette, QDesktopServices
from crawler.car_crawler import CarInfo
from utils.image_loader import image_loader, image_cache


class CarWidget(QFrame):
    """汽车信息卡片组件"""
    
    # 信号：点击查看详情
    detail_clicked = pyqtSignal(CarInfo)
    
    def __init__(self, car_info: CarInfo, parent=None):
        super().__init__(parent)
        self.car_info = car_info
        self.image_label = None
        self.setup_ui()
        self.setup_style()
        self.load_image()
    
    def setup_ui(self):
        """设置界面"""
        self.setFrameStyle(QFrame.Box)
        self.setLineWidth(1)
        
        # 主布局
        main_layout = QHBoxLayout(self)
        main_layout.setContentsMargins(20, 20, 20, 20)  # 增加内边距
        main_layout.setSpacing(20)  # 增加图片和信息区域之间的间距
        
        # 左侧：图片
        self.image_label = QLabel()
        self.image_label.setFixedSize(180, 120)
        self.image_label.setAlignment(Qt.AlignCenter)
        self.image_label.setStyleSheet("""
            QLabel {
                border: 2px solid #e0e6ed;
                border-radius: 8px;
                background-color: white;
                padding: 5px;
            }
        """)
        self.image_label.setText("加载中...")
        main_layout.addWidget(self.image_label)
        
        # 右侧：信息区域
        info_layout = QVBoxLayout()
        info_layout.setSpacing(12)  # 增加信息项之间的间距
        
        # 排名和车名
        title_layout = QHBoxLayout()
        
        # 排名标签
        rank_label = QLabel(f"#{self.car_info.rank}")
        rank_label.setFont(QFont("Microsoft YaHei", 14, QFont.Bold))  # 减小字体
        rank_label.setStyleSheet("""
            QLabel {
                color: #e74c3c;
                background-color: #fff5f5;
                border: 2px solid #e74c3c;
                border-radius: 12px;
                padding: 3px 8px;
                min-width: 35px;
                max-width: 50px;
                min-height: 20px;
                max-height: 25px;
            }
        """)
        rank_label.setAlignment(Qt.AlignCenter)
        title_layout.addWidget(rank_label)
        
        # 车名
        name_label = QLabel(self.car_info.name)
        name_label.setFont(QFont("Microsoft YaHei", 13, QFont.Bold))  # 稍微减小字体
        name_label.setStyleSheet("color: #2c3e50; margin-left: 8px; margin-top: 2px;")
        name_label.setWordWrap(True)  # 允许换行
        title_layout.addWidget(name_label)
        title_layout.addStretch()
        
        info_layout.addLayout(title_layout)
        
        # 评分
        score_layout = QHBoxLayout()
        score_layout.addWidget(QLabel("评分:"))
        score_value = QLabel(f"{self.car_info.score:.1f}")
        score_value.setFont(QFont("Microsoft YaHei", 12, QFont.Bold))
        score_value.setStyleSheet("color: #f39c12;")
        score_layout.addWidget(score_value)
        score_layout.addStretch()
        info_layout.addLayout(score_layout)
        
        # 价格
        price_layout = QHBoxLayout()
        price_layout.addWidget(QLabel("价格:"))
        price_value = QLabel(self.car_info.price)
        price_value.setFont(QFont("Microsoft YaHei", 12, QFont.Bold))
        price_value.setStyleSheet("color: #27ae60;")
        price_layout.addWidget(price_value)
        price_layout.addStretch()
        info_layout.addLayout(price_layout)
        
        # 销量
        sales_layout = QHBoxLayout()
        sales_layout.addWidget(QLabel("销量:"))
        sales_value = QLabel(f"{self.car_info.sales:,}")
        sales_value.setFont(QFont("Microsoft YaHei", 12))
        sales_value.setStyleSheet("color: #8e44ad;")
        sales_layout.addWidget(sales_value)
        sales_layout.addStretch()
        info_layout.addLayout(sales_layout)

        # 添加一些垂直间距
        info_layout.addSpacing(10)

        # 按钮区域
        button_layout = QHBoxLayout()
        
        # 查看详情按钮
        detail_btn = QPushButton("查看详情")
        detail_btn.setFont(QFont("Microsoft YaHei", 9))  # 稍微减小字体
        detail_btn.setStyleSheet("""
            QPushButton {
                background-color: #3498db;
                color: white;
                border: none;
                border-radius: 6px;
                padding: 6px 12px;
                font-weight: bold;
                min-height: 25px;
                max-height: 30px;
            }
            QPushButton:hover {
                background-color: #2980b9;
            }
            QPushButton:pressed {
                background-color: #21618c;
            }
        """)
        detail_btn.clicked.connect(self.on_detail_clicked)
        button_layout.addWidget(detail_btn)
        
        # 访问官网按钮
        visit_btn = QPushButton("访问官网")
        visit_btn.setFont(QFont("Microsoft YaHei", 9))  # 稍微减小字体
        visit_btn.setStyleSheet("""
            QPushButton {
                background-color: #95a5a6;
                color: white;
                border: none;
                border-radius: 6px;
                padding: 6px 12px;
                font-weight: bold;
                min-height: 25px;
                max-height: 30px;
            }
            QPushButton:hover {
                background-color: #7f8c8d;
            }
            QPushButton:pressed {
                background-color: #6c7b7d;
            }
        """)
        visit_btn.clicked.connect(self.on_visit_clicked)
        button_layout.addWidget(visit_btn)
        
        button_layout.addStretch()
        info_layout.addLayout(button_layout)

        # 移除弹性空间，让内容紧凑排列
        main_layout.addLayout(info_layout)
        
        # 设置尺寸策略
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        self.setFixedHeight(220)  # 调整为合适的高度
    
    def setup_style(self):
        """设置样式"""
        self.setStyleSheet("""
            CarWidget {
                background-color: white;
                border: 1px solid #e0e0e0;
                border-radius: 12px;
                margin: 5px;
            }
            CarWidget:hover {
                border: 2px solid #3498db;
                box-shadow: 0 4px 8px rgba(52, 152, 219, 0.2);
            }
            QLabel {
                color: #34495e;
                font-family: "Microsoft YaHei";
            }
        """)
    
    def load_image(self):
        """加载汽车图片"""
        if self.car_info.image_url:
            # 先检查缓存
            cached_pixmap = image_cache.get_cached_image(
                self.car_info.image_url, 
                (180, 120)
            )
            
            if not cached_pixmap.isNull():
                self.image_label.setPixmap(cached_pixmap)
            else:
                # 连接信号并开始加载
                image_loader.image_loaded.connect(self.on_image_loaded)
                image_loader.image_failed.connect(self.on_image_failed)
                image_loader.load_image(self.car_info.image_url, (180, 120))
        else:
            self.image_label.setText("暂无图片")
    
    def on_image_loaded(self, image_url: str, pixmap: QPixmap):
        """图片加载完成"""
        if image_url == self.car_info.image_url:
            self.image_label.setPixmap(pixmap)
    
    def on_image_failed(self, image_url: str, error_message: str):
        """图片加载失败"""
        if image_url == self.car_info.image_url:
            self.image_label.setText("图片加载失败")
            print(f"图片加载失败: {error_message}")
    
    def on_detail_clicked(self):
        """点击查看详情"""
        self.detail_clicked.emit(self.car_info)
    
    def on_visit_clicked(self):
        """点击访问官网"""
        if self.car_info.detail_url:
            QDesktopServices.openUrl(QUrl(self.car_info.detail_url))


class CarListWidget(QWidget):
    """汽车列表组件"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.car_widgets = []
        self.setup_ui()
    
    def setup_ui(self):
        """设置界面"""
        self.layout = QVBoxLayout(self)
        self.layout.setContentsMargins(15, 15, 15, 15)
        self.layout.setSpacing(15)  # 增加卡片间距

        # 添加弹性空间
        self.layout.addStretch()
    
    def add_car(self, car_info: CarInfo):
        """添加汽车信息"""
        car_widget = CarWidget(car_info)
        car_widget.detail_clicked.connect(self.on_car_detail_clicked)
        
        # 插入到弹性空间之前
        self.layout.insertWidget(len(self.car_widgets), car_widget)
        self.car_widgets.append(car_widget)
    
    def clear_cars(self):
        """清空汽车列表"""
        for widget in self.car_widgets:
            widget.deleteLater()
        self.car_widgets.clear()
    
    def on_car_detail_clicked(self, car_info):
        """处理汽车详情点击事件"""
        print(f"查看汽车详情: {car_info.name}")

        # 将CarInfo对象转换为字典格式
        car_dict = {
            'rank': car_info.rank,
            'name': car_info.name,
            'score': car_info.score,
            'price': car_info.price,
            'sales': car_info.sales,
            'image_url': getattr(car_info, 'image_url', ''),
            'detail_url': getattr(car_info, 'detail_url', '')
        }

        # 导入并显示详情对话框
        try:
            from ui.main_window import CarDetailDialog
            dialog = CarDetailDialog(car_dict, self)
            dialog.exec_()
        except ImportError as e:
            print(f"无法导入详情对话框: {e}")
            QMessageBox.information(self, "详情", f"车名: {car_info.name}\n评分: {car_info.score}\n价格: {car_info.price}\n销量: {car_info.sales}")
